package com.example.mychatgpt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.mychatgpt.entity.records;
import com.example.mychatgpt.entity.records_item;
import com.example.mychatgpt.service.recordsService;
import com.example.mychatgpt.utils.R;
import com.example.mychatgpt.utils.utils;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
public class recordsController {
    @Autowired
    recordsService recordsservice;
    @GetMapping("/records/getAllRecordsByAccount")
    R getAllRecords(String account){
        List<Map<String, Object>> ans=recordsservice.getRecordsByAccount(account);
        if(ans.size()==0){
            return new R(false,"未找到账户对应记录",null);
        }
        Map<String,Object> toSend=new HashMap<>();
        toSend.put("records",ans);
        return new R(true,"成功",toSend);
    }
    @GetMapping("/records/getAllRecordsItemById")
    R getAllRecords(int id){
        List<Map<String, Object>> ans=recordsservice.getRecordsItemByRecordsId(id);
        if(ans.size()==0){
            return new R(false,"未找到对应记录条目",null);
        }
        Map<String,Object> toSend=new HashMap<>();
        toSend.put("recordsItem",ans);
        return new R(true,"成功",toSend);
    }
    @PostMapping("/records/query")
    R query(@RequestBody Map<String,Object> data){
        try{
            String query=utils.correctString(data.get("query").toString());
            int recordsId= (int) data.get("recordsId");
            List<Map<String,Object>> ans= recordsservice.getRecordsItemByRecordsId(recordsId);
            if(recordsservice.getRecordsById(recordsId).size()==0){
                return new R(false,"请求失败",null);
            }
            OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(180, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            StringBuilder tmp=new StringBuilder("{" +
                    "    \"system_prompt\": \"\"," +
                    "    \"history\": [");
            for (Map<String, Object> an : ans) {
                tmp.append("{\"role\":\"").append(an.get("role")).append("\",\"content\":\"").append(utils.correctString((String) an.get("content"))).append("\"},");
            }
            tmp.append("{\"role\":\"").append("Human").append("\",\"content\":\"").append(query).append("\"}");
            tmp.append("],\"n\": 1,\"best_of\": 1,\"presence_penalty\": 1.2,\"frequency_penalty\": 0.2,\"temperature\": 0.3,\"top_p\": 0.95,\"top_k\": 50,\"use_beam_search\": false,\"stop\": [],\"ignore_eos\": false,\"logprobs\": null, \"max_new_tokens\": 2048}");
            System.out.println("****\n"+tmp+"\n****");
            okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, String.valueOf(tmp));
            Request request = new Request.Builder()
                    .url("http://127.0.0.1:8001/generate")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            JSONObject jsonObject= JSON.parseObject(Objects.requireNonNull(response.body()).string());
            String answer=jsonObject.getString("response");
            List<records_item> toSend=new ArrayList<>();
            toSend.add(recordsservice.insertRecordsItem("Human",query ,recordsId));
            toSend.add(recordsservice.insertRecordsItem("Assistant",utils.correctString(answer.substring(0,Math.min(answer.length(),1000))),recordsId));
            Map<String,Object> myContent=new HashMap<>();
            myContent.put("recordsItem",toSend);
            return new R(true,"回答成功",myContent);
        }catch (Exception e){
            System.out.println(e.toString());
            return new R(false,"请求失败",null);
        }
    }
    @GetMapping("/records/add/{account}")
    public R  addRecords(@PathVariable String account){
        try{
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            Date date = new Date();
            String formattedDate = formatter.format(date);
            recordsservice.addRecords(formattedDate,account);
            return new R(true,"添加成功",null);
        }catch (Exception e){
            System.out.println(e.toString());
            return new R(false,"添加失败",null);
        }
    }

}
